﻿using System;
using System.Data;
using System.Configuration;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Xml;
using System.Text;
using System.IO;
using System.Net.Mail;
using System.Net;
using System.Security.Cryptography;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Collections;


/// <summary>
/// Descripción breve de Utility
/// </summary>
public class Utility
{
     
	public Utility()
	{
		//
		// TODO: Agregar aquí la lógica del constructor
		//
	}

    public static string cifrado(string texto)
    {
        string result = null;
        try
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(texto);
            bs = x.ComputeHash(bs);
            string password;
            System.Text.StringBuilder smd = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                smd.Append(b.ToString("x2").ToLower());
            }
            result = smd.ToString();
        }
        catch (Exception e)
        {

            return null;
        }
        return result;

    }


    //para generar xml
    public static string setXml(string user, string pass, int app, int perfilid)
    {
        string result = "";
        
        result = "<?xml version=\"1.0\" encoding=\"utf-8\"?><datos_login>";
        result = result+ "<usuarioid>";
        result= result+user;
        result = result + "</usuarioid> <contrasena>"+ pass;
        result = result + "</contrasena><aplicacionid>" + app + "</aplicacionid><perfilid>" + perfilid + "</perfilid></datos_login>";
        return result;
                       
        
        }

    
       
    
    

    //para consumir ws de login, lee xml de respuesta
    public static rUser getRUser(string sdatosin)
    {
        rUser ruser = null;

        try
        {
            XmlDocument xDoc = new XmlDocument();

            xDoc.Load(new StringReader(sdatosin));

            XmlElement datosrespuesta = xDoc.DocumentElement;
            ruser = new rUser();
            foreach (XmlElement nodo in datosrespuesta)
            {
                if (nodo.Name.Equals("respuestaid"))
                {

                    int rid = int.Parse(nodo.InnerText);
                    ruser.setRespuestaId(rid);
                }
                if (nodo.Name.Equals("usuarioid"))
                {

                    ruser.setUsuarioId(nodo.InnerText);
                }
                if (nodo.Name.Equals("pass"))
                {

                    ruser.pass = nodo.InnerText;
                }
                if (nodo.Name.Equals("nombre"))
                {

                    ruser.setNombre(nodo.InnerText);
                }
                if (nodo.Name.Equals("apellido"))
                {

                    ruser.setApellido(nodo.InnerText);
                }
                if (nodo.Name.Equals("alias"))
                {

                    ruser.setAlias(nodo.InnerText);
                }
                if (nodo.Name.Equals("perfilid"))
                {
                    ruser.setPerfilId(nodo.InnerText);
                }
                if (nodo.Name.Equals("group"))
                {
                    ruser.setGroup(nodo.InnerText);
                }
                if (nodo.Name.Equals("permiso"))
                {
                    long rper = long.Parse(nodo.InnerText);
                    ruser.setPermiso(rper);
                }
                if (nodo.Name.Equals("comp-name"))
                {

                    ruser.compname= nodo.InnerText;
                }
                

                if (nodo.Name.Equals("logo"))
                {

                    ruser.setLogo(nodo.InnerText);
                }
                if (nodo.Name.Equals("email"))
                {

                    ruser.setEmail(nodo.InnerText);
                }
                if (nodo.Name.Equals("title"))
                {

                    ruser.title = nodo.InnerText;
                }
                if (nodo.Name.Equals("where1"))
                {

                    ruser.setWhere(nodo.InnerText);
                }
                
                if (nodo.Name.Equals("where2"))
                {

                    ruser.setWhere2(nodo.InnerText);
                }
                if (nodo.Name.Equals("where3"))
                {

                    ruser.setWhere3(nodo.InnerText);
                }
                if (nodo.Name.Equals("permisouser"))
                {
                    long p = long.Parse(nodo.InnerText);
                    ruser.setPermisoUser(p);
                }
                if (nodo.Name.Equals("restricted"))
                {
                    long p = long.Parse(nodo.InnerText);
                    ruser.setRestricted(p);
                }
                if (nodo.Name.Equals("restrictedrol"))
                {
                    long p = long.Parse(nodo.InnerText);
                    ruser.restrictedrol=p;
                }

                if (nodo.Name.Equals("estado"))
                {

                    ruser.estado= int.Parse(nodo.InnerText);
                }

                if (nodo.Name.Equals("logo"))
                {
                    ruser.setLogo(nodo.InnerText);
                }

                if (nodo.Name.Equals("companies")) {
                   
                    ruser.companies = new ArrayList();
                    int pos = 0;
                     XmlNodeList companies = nodo.ChildNodes;
                     foreach (XmlElement company in companies)
                     {
                         RE_GenericBean rcompanies = new RE_GenericBean();
                         foreach (XmlElement item in company)
                         {
                             if (item.Name.Equals("id"))
                             {
                                 rcompanies.intC1 = int.Parse(item.InnerText);
                             }
                             if (item.Name.Equals("nombre"))
                             {
                                 rcompanies.strC1 = item.InnerText;
                             }
                         }
                         ruser.companies.Add(rcompanies);
                         
                     }
                
                }

                if (nodo.Name.Equals("accounts"))
                {
                    XmlNodeList accounts = nodo.ChildNodes;
                   
                    ruser.accounts = new ArrayList();
                    foreach (XmlElement acc in accounts)
                    {
                        RE_GenericBean racc = new RE_GenericBean();
                        foreach (XmlElement item in acc)
                        {
                            if (item.Name.Equals("id"))
                            {
                                racc.intC1 = int.Parse(item.InnerText);
                            }
                            if (item.Name.Equals("nombre"))
                            {
                                racc.strC1 = item.InnerText;
                            }
                        }
                        ruser.accounts.Add(racc);
                    }
                   
                }

                if (nodo.Name.Equals("states"))
                {
                  
                    XmlNodeList states = nodo.ChildNodes;
                    ruser.states = new ArrayList();
                    foreach (XmlElement state in states )
                    {
                        RE_GenericBean rstate = new RE_GenericBean();
                        foreach (XmlElement item in state)
                        {
                            if (item.Name.Equals("id"))
                            {
                                rstate.intC1 = int.Parse(item.InnerText);
                            }
                        }
                        ruser.states.Add(rstate);

                    }


                }
                if (nodo.Name.Equals("counties"))
                {
                    
                    XmlNodeList counties = nodo.ChildNodes;
                    ruser.counties = new ArrayList();
                    foreach (XmlElement county in counties)
                    {
                        RE_GenericBean rcounty = new RE_GenericBean();
                        foreach (XmlElement item in county)
                        {
                            if (item.Name.Equals("id"))
                            {
                                rcounty.intC1 = int.Parse(item.InnerText);
                            }
                        }
                        ruser.counties.Add(rcounty);

                    }


                }
                if (nodo.Name.Equals("perfiles"))
                {
                   
                    XmlNodeList perfiles = nodo.ChildNodes;
                    ruser.perfiles = new ArrayList();
                    foreach (XmlElement perfil in perfiles)
                    {
                        RE_GenericBean rperfil = new RE_GenericBean();
                        foreach (XmlElement item in perfil)
                        {
                            if (item.Name.Equals("id"))
                            {
                                rperfil.intC1 = int.Parse(item.InnerText);
                            }
                            if (item.Name.Equals("nombre"))
                            {
                                rperfil.strC1 = item.InnerText;
                            }
                        }
                        ruser.perfiles.Add(rperfil);
                    }


                }
                if (nodo.Name.Equals("permisos"))
                {

                    XmlNodeList permisos = nodo.ChildNodes;
                    ruser.permisos = new ArrayList();
                    foreach (XmlElement permiso in permisos)
                    {
                        RE_GenericBean rpermisos = new RE_GenericBean();
                        foreach (XmlElement item in permiso)
                        {
                            if (item.Name.Equals("usuID"))
                            {
                                rpermisos.strC1 = item.InnerText;
                            }
                            if (item.Name.Equals("pageID"))
                            {
                                rpermisos.intC1 = int.Parse(item.InnerText);
                            }
                            if (item.Name.Equals("permit"))
                            {
                                rpermisos.int64C1 = long.Parse(item.InnerText);
                            }
                            if (item.Name.Equals("restricted"))
                            {
                                rpermisos.int64C2 = long.Parse(item.InnerText);
                            }
                        }
                        ruser.permisos.Add(rpermisos);
                    }


                }
                if (nodo.Name.Equals("prices"))
                {
                   
                    ruser.prices = new ArrayList();
                    XmlNodeList prices = nodo.ChildNodes;
                    foreach (XmlElement price in prices)
                    {
                        RE_GenericBean rprice = new RE_GenericBean();
                        foreach (XmlElement item in price)
                        {
                            if (item.Name.Equals("product_id"))
                            {
                                rprice.intC1 = int.Parse(item.InnerText);
                            }
                            if (item.Name.Equals("price"))
                            {
                                rprice.strC1 = item.InnerText;
                            }
                        }
                        ruser.prices.Add(rprice);
                    }


                }

                if (nodo.Name.Equals("direcciones"))
                {
                    ruser.direcciones = new ArrayList();
                    XmlNodeList direcciones = nodo.ChildNodes;
                    foreach (XmlElement direccion in direcciones)
                    {
                        RE_Direccion rdir = new RE_Direccion();
                        foreach (XmlElement item in direccion)
                        {
                            if (!item.Name.Equals(""))
                            {
                                switch (item.Name)
                                {
                                    case "uidID":
                                        {
                                            rdir.uinID = int.Parse(item.InnerText);
                                            break;
                                        }
                                    case "add1":
                                        {
                                            rdir.stnumber = item.InnerText;
                                            break;
                                        }
                                    case "add2":
                                        {
                                            rdir.stadd = item.InnerText;
                                            break;
                                        }
                                    case "city":
                                        {
                                            rdir.city = item.InnerText;
                                            break;
                                        }
                                    case "state":
                                        {
                                            rdir.state = item.InnerText;
                                            break;
                                        }
                                    case "zip":
                                        {
                                            rdir.zip = item.InnerText;
                                            break;
                                        }
                                    case "office_phone":
                                        {
                                            rdir.telof = item.InnerText;
                                            break;
                                        }
                                    case "cell_phone":
                                        {
                                            rdir.telcel = item.InnerText;
                                            break;
                                        }
                                    case "fax":
                                        {
                                            rdir.fax = item.InnerText;
                                            break;
                                        }
                                    case "tipo":
                                        {
                                            rdir.tipodir = int.Parse(item.InnerText);
                                            break;
                                        }
                                }
                            }
                            if(item.Name.Equals("credit_card"))
                            {
                                XmlNodeList tarjetas = item.ChildNodes;
                                RE_CreditCard rcredit = new RE_CreditCard();
                                foreach (XmlElement tarjeta in tarjetas)
                                {
                                    if (!tarjeta.InnerText.Equals(""))
                                    {
                                        switch (tarjeta.Name)
                                        {
                                            case "tacID":
                                                {
                                                    rcredit.tacID = int.Parse(tarjeta.InnerText);
                                                    break;
                                                }
                                            case "namecreditcard":
                                                {
                                                    rcredit.name = tarjeta.InnerText;
                                                    break;
                                                }
                                            case "creditcard":
                                                {
                                                    rcredit.number = tarjeta.InnerText;
                                                    break;
                                                }
                                            case "expdate":
                                                {
                                                    rcredit.expdate = tarjeta.InnerText;
                                                    break;
                                                }
                                            case "ccv":
                                                {
                                                    rcredit.ccv = int.Parse(tarjeta.InnerText);
                                                    break;
                                                }
                                        }
                                    }
                                }

                                if (rdir.tarjetas == null) rdir.tarjetas = new ArrayList();
                                rdir.tarjetas.Add(rcredit);
                            }
                        }
                        if (ruser.direcciones == null) ruser.direcciones = new ArrayList();
                        ruser.direcciones.Add(rdir);
                    }
                }

                if (nodo.Name.Equals("counties"))
                {

                    XmlNodeList counties = nodo.ChildNodes;
                    ruser.counties = new ArrayList();
                    foreach (XmlElement county in counties)
                    {
                        RE_GenericBean rcounty = new RE_GenericBean();
                        foreach (XmlElement item in county)
                        {
                            if (item.Name.Equals("id"))
                            {
                                rcounty.intC1 = int.Parse(item.InnerText);
                            }
                        }
                        ruser.counties.Add(rcounty);

                    }


                }
                if (nodo.Name.Equals("permisos"))
                {

                    XmlNodeList permisos = nodo.ChildNodes;
                    ruser.permisos = new ArrayList();
                    foreach (XmlElement permiso in permisos)
                    {
                        RE_GenericBean rpermiso = new RE_GenericBean();
                        foreach (XmlElement item in permiso)
                        {
                            if (item.Name.Equals("pageID"))
                            {
                                rpermiso.intC1 = int.Parse(item.InnerText);
                            }
                            if (item.Name.Equals("permit"))
                            {
                                rpermiso.int64C1 = Int64.Parse(item.InnerText);
                            }
                            if (item.Name.Equals("restricted"))
                            {
                                rpermiso.int64C2 = Int64.Parse(item.InnerText);
                            }
                        }
                        ruser.permisos.Add(rpermiso);
                    }


                }




            }
        }
        catch (Exception e)
        {

        }
        return ruser;
}


    public static rReg getRReg(string sdatosreg)
    {
        rReg rreg = new rReg();
        try{

        XmlDocument xDoc = new XmlDocument();

        xDoc.Load(new StringReader(sdatosreg));

        XmlElement datosrespuesta = xDoc.DocumentElement;
        
        
            foreach (XmlElement nodo in datosrespuesta)
            {
                if (nodo.Name.Equals("respuestaid"))
                {

                    int rid = int.Parse(nodo.InnerText);
                    rreg.setRespuestaId(rid);
                }
                if (nodo.Name.Equals("mensaje"))
                {

                    rreg.setMensaje(nodo.InnerText);
                }
                if (nodo.Name.Equals("userid"))
                {

                    int uid = int.Parse(nodo.InnerText);
                    rreg.setUserId(uid);
                }

            }
        }
        catch (Exception e)
        {
            rreg.setRespuestaId(0);
            rreg.setMensaje("Error");

        }
        return rreg;
    }
    public static rActivate getRAct(string sdatosreg)
    {
        rActivate ract = new rActivate();
        try
        {

            XmlDocument xDoc = new XmlDocument();

            xDoc.Load(new StringReader(sdatosreg));

            XmlElement datosrespuesta = xDoc.DocumentElement;


            foreach (XmlElement nodo in datosrespuesta)
            {
                if (nodo.Name.Equals("respuestaid"))
                {

                    int rid = int.Parse(nodo.InnerText);
                    ract.setRespuestaId(rid);
                }
                if (nodo.Name.Equals("mensaje"))
                {

                    ract.setMensaje(nodo.InnerText);
                }
               

            }
        }
        catch (Exception e)
        {
            ract.setRespuestaId(0);
            ract.setMensaje("Error");

        }
        return ract;
    }
    
    public static string sendMail(string mailfrom, string mail, string Subject,string body, string cco){
        string result;
        result = "";
        try
        {
            if (!mail.Equals(""))
            {
                MailMessage message = new MailMessage();
                message.From = new MailAddress(mailfrom);
                if (cco != "")
                {
                    foreach (string copiar_a in cco.Split(';'))
                    {
                        message.Bcc.Add(cco);
                    }
                }
                if (mail != "")
                {
                    foreach (string copiar_a in mail.Split(';'))
                    {
                        message.To.Add(new MailAddress(copiar_a));
                    }
                }

                //message.To.Add(new MailAddress(mail));
                message.Subject = Subject;
                message.IsBodyHtml = true;
                message.Body = body;

                SmtpClient client = new SmtpClient();
               
                client.Host = "s2smtpout.secureserver.net";
                //client.Host = "smtp.gmail.com";
                client.EnableSsl = false;
                client.UseDefaultCredentials = true;
                client.Port = 25;

                //client.Timeout = 4000;
                client.Credentials = new NetworkCredential(mailfrom, "photos1");
                client.ServicePoint.MaxIdleTime = 0;
                client.ServicePoint.ConnectionLimit = 1;
                client.Send(message);
                result = "ok";
                //client.Dispose();
                //System.Threading.Thread.Sleep(TimeSpan.FromSeconds(30));

            }
        }
        catch (Exception e)
        {

            writeError(DateTime.Now + " Send Mail Error. to  "+mailfrom+" " + e.Message + " _" + e.StackTrace);

            
            result = "";
        }
        
            return result;
    }


    public static void writeError(string error) {

        if (!error.Equals("String was not recognized as a valid DateTime.") && !error.Equals("Root element is missing.")){
        try
        {
            string ruta = "c:\\TEMP\\log_bpo_"+DateTime.Now.Date.Month.ToString()+"_"+DateTime.Now.Date.Day.ToString()+"_"+DateTime.Now.Date.Year.ToString()+".txt";
            StreamWriter escritor = new StreamWriter(ruta, true);
            escritor.WriteLine(DateTime.Now + " " + error);

            escritor.Close();
        }
        catch (Exception e){
            
        }
        }
    }

    public static string sendMailAtach(string mailfrom, string mail, string Subject, string body, string[] attach, string cco)
    {
        string result;
        result = "";
        try
        {
            if (!mail.Equals(""))
            {
                MailMessage message = new MailMessage();
                message.From = new MailAddress(mailfrom);
                if (mail != "")
                {
                    foreach (string copiar_a in mail.Split(';'))
                    {
                        message.To.Add(new MailAddress(copiar_a));
                    }
                }
                if (cco != "")
                {
                    foreach (string copiar_a in cco.Split(';'))
                    {
                        message.Bcc.Add(cco);
                    }
                }
                //message.To.Add(new MailAddress(mail));
                message.Subject = Subject;
                message.IsBodyHtml = true;
                message.Body = body;

                for (int i = 0; i < attach.Length ; i++ ) {
                    if (attach[i]!=null){
                        try
                        {
                            message.Attachments.Add(new Attachment(@attach[i]));
                        } catch (Exception exx){
                        Utility.writeError("Error al adjuntar photo "+ i);
                    }
                    
                    }
                }
               
                SmtpClient client = new SmtpClient();
              
                
                client.Host = "s2smtpout.secureserver.net";
                client.EnableSsl = false;
                client.UseDefaultCredentials = true;
                client.Port = 25;
                client.Credentials = new NetworkCredential("newclient@bpophotos.com", "photos1");
                client.ServicePoint.MaxIdleTime = 0;
                client.ServicePoint.ConnectionLimit = 1;
                client.Send(message);
                result = "ok";
               // client.Send (new MailMessage());
            }
        }
        catch (Exception e)
        {

            writeError("Error envio mensaje attach "+e.Message);
            
            result = "";
        }
        return result;
    }
    
    public static string ComputeHash(string   plainText,
                                     string   hashAlgorithm,
                                     byte[]   saltBytes)
    {
        // If salt is not specified, generate it on the fly.
        if (saltBytes == null)
        {
            // Define min and max salt sizes.
            int minSaltSize = 4;
            int maxSaltSize = 8;

            // Generate a random number for the size of the salt.
            Random  random = new Random();
            int saltSize = random.Next(minSaltSize, maxSaltSize);

            // Allocate a byte array, which will hold the salt.
            saltBytes = new byte[saltSize];

            // Initialize a random number generator.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            // Fill the salt with cryptographically strong byte values.
            rng.GetNonZeroBytes(saltBytes); 
        }
        
        // Convert plain text into a byte array.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        
        // Allocate array, which will hold plain text and salt.
        byte[] plainTextWithSaltBytes = 
                new byte[plainTextBytes.Length + saltBytes.Length];

        // Copy plain text bytes into resulting array.
        for (int i=0; i < plainTextBytes.Length; i++)
            plainTextWithSaltBytes[i] = plainTextBytes[i];
        
        // Append salt bytes to the resulting array.
        for (int i=0; i < saltBytes.Length; i++)
            plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];

        // Because we support multiple hashing algorithms, we must define
        // hash object as a common (abstract) base class. We will specify the
        // actual hashing algorithm class later during object creation.
        HashAlgorithm hash;
        
        // Make sure hashing algorithm name is specified.
        if (hashAlgorithm == null)
            hashAlgorithm = "";
        
        // Initialize appropriate hashing algorithm class.
        switch (hashAlgorithm.ToUpper())
        {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            default:
                hash = new MD5CryptoServiceProvider();
                break;
        }
        
        // Compute hash value of our plain text with appended salt.
        byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);
        
        // Create array which will hold hash and original salt bytes.
        byte[] hashWithSaltBytes = new byte[hashBytes.Length + 
                                            saltBytes.Length];
        
        // Copy hash bytes into resulting array.
        for (int i=0; i < hashBytes.Length; i++)
            hashWithSaltBytes[i] = hashBytes[i];
            
        // Append salt bytes to the result.
        for (int i=0; i < saltBytes.Length; i++)
            hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];
            
        // Convert result into a base64-encoded string.
        string hashValue = Convert.ToBase64String(hashWithSaltBytes);
        
        // Return the result.
        return hashValue;
    }

    /// <summary>
    /// Compares a hash of the specified plain text value to a given hash
    /// value. Plain text is hashed with the same salt value as the original
    /// hash.
    /// </summary>
    /// <param name="plainText">
    /// Plain text to be verified against the specified hash. The function
    /// does not check whether this parameter is null.
    /// </param>
    /// <param name="hashAlgorithm">
    /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1", 
    /// "SHA256", "SHA384", and "SHA512" (if any other value is specified,
    /// MD5 hashing algorithm will be used). This value is case-insensitive.
    /// </param>
    /// <param name="hashValue">
    /// Base64-encoded hash value produced by ComputeHash function. This value
    /// includes the original salt appended to it.
    /// </param>
    /// <returns>
    /// If computed hash mathes the specified hash the function the return
    /// value is true; otherwise, the function returns false.
    /// </returns>
    public static bool VerifyHash(string   plainText,
                                  string   hashAlgorithm,
                                  string   hashValue)
    {
        // Convert base64-encoded hash value into a byte array.
        byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);
        
        // We must know size of hash (without salt).
        int hashSizeInBits, hashSizeInBytes;
        
        // Make sure that hashing algorithm name is specified.
        if (hashAlgorithm == null)
            hashAlgorithm = "";
        
        // Size of hash is based on the specified algorithm.
        switch (hashAlgorithm.ToUpper())
        {
            case "SHA1":
                hashSizeInBits = 160;
                break;

            case "SHA256":
                hashSizeInBits = 256;
                break;

            case "SHA384":
                hashSizeInBits = 384;
                break;

            case "SHA512":
                hashSizeInBits = 512;
                break;

            default: // Must be MD5
                hashSizeInBits = 128;
                break;
        }

        // Convert size of hash from bits to bytes.
        hashSizeInBytes = hashSizeInBits / 8;

        // Make sure that the specified hash value is long enough.
        if (hashWithSaltBytes.Length < hashSizeInBytes)
            return false;

        // Allocate array to hold original salt bytes retrieved from hash.
        byte[] saltBytes = new byte[hashWithSaltBytes.Length - 
                                    hashSizeInBytes];

        // Copy salt from the end of the hash to the new array.
        for (int i=0; i < saltBytes.Length; i++)
            saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i];

        // Compute a new hash string.
        string expectedHashString = 
                    ComputeHash(plainText, hashAlgorithm, saltBytes);

        // If the computed hash matches the specified hash,
        // the plain text value must be correct.
        return (hashValue == expectedHashString);
    }
    public static DataSet getUsuariosporPerfil(string sdatos)
    {
        DataSet result= new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("user");
        result.Tables["Tabla"].Columns.Add("lastname");
        result.Tables["Tabla"].Columns.Add("name");
        result.Tables["Tabla"].Columns.Add("group");
        result.Tables["Tabla"].Columns.Add("profilename");
        result.Tables["Tabla"].Columns.Add("profile");
        result.Tables["Tabla"].Columns.Add("alias");
        result.Tables["Tabla"].Columns.Add("comp-name");
        result.Tables["Tabla"].Columns.Add("email");

        if (!sdatos.Equals(""))
        {
            try
            {

                XmlDocument xDoc = new XmlDocument();

                xDoc.Load(new StringReader(sdatos));

                XmlElement datosrespuesta = xDoc.DocumentElement;

                XmlNodeList users = xDoc.GetElementsByTagName("lista_usuarios");
                XmlNodeList respuesta = xDoc.GetElementsByTagName("respuestaID");

                XmlNodeList lista = ((XmlElement)users[0]).GetElementsByTagName("datos_registro");

                foreach (XmlElement nodo in lista)
                {
                    XmlNodeList nUser = nodo.GetElementsByTagName("user");
                    XmlNodeList nName = nodo.GetElementsByTagName("name");
                    XmlNodeList nLastname = nodo.GetElementsByTagName("lastname");
                    XmlNodeList nCompname = nodo.GetElementsByTagName("comp-name");
                    XmlNodeList nAlias = nodo.GetElementsByTagName("alias");
                    XmlNodeList nEmail = nodo.GetElementsByTagName("email");
                    XmlNodeList nProfile = nodo.GetElementsByTagName("profile");
                    XmlNodeList nProfilename = nodo.GetElementsByTagName("profilename");
                    XmlNodeList nGroup = nodo.GetElementsByTagName("group");


                    DataRow fila;
                    fila = result.Tables[0].NewRow();
                    fila["user"] = nUser[0].InnerText;
                    fila["name"] = nName[0].InnerText;
                    fila["lastname"] = nLastname[0].InnerText;
                    fila["comp-name"] = nCompname[0].InnerText;
                    fila["alias"] = nAlias[0].InnerText;
                    fila["email"] = nEmail[0].InnerText;
                    fila["profile"] = nProfile[0].InnerText;
                    fila["profilename"] = nProfilename[0].InnerText;
                    fila["group"] = nGroup[0].InnerText;
                    result.Tables[0].Rows.Add(fila);
                }

            }
            catch (Exception e)
            {
                Utility.writeError(e.Message);
                result = null;
            }
        }
        return result;
    }

    public static DataSet getUsuariosInactivos(string sdatos)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("user");
        result.Tables["Tabla"].Columns.Add("lastname");
        result.Tables["Tabla"].Columns.Add("name");
        result.Tables["Tabla"].Columns.Add("group");
        result.Tables["Tabla"].Columns.Add("profilename");
        result.Tables["Tabla"].Columns.Add("profile");
        result.Tables["Tabla"].Columns.Add("alias");
        result.Tables["Tabla"].Columns.Add("comp-name");
        result.Tables["Tabla"].Columns.Add("email");


        try
        {

            XmlDocument xDoc = new XmlDocument();

            xDoc.Load(new StringReader(sdatos));

            XmlElement datosrespuesta = xDoc.DocumentElement;

            XmlNodeList users = xDoc.GetElementsByTagName("lista_usuarios");
            XmlNodeList respuesta = xDoc.GetElementsByTagName("respuestaID");

            XmlNodeList lista = ((XmlElement)users[0]).GetElementsByTagName("datos_registro");

            foreach (XmlElement nodo in lista)
            {
                XmlNodeList nUser = nodo.GetElementsByTagName("user");
                XmlNodeList nName = nodo.GetElementsByTagName("name");
                XmlNodeList nLastname = nodo.GetElementsByTagName("lastname");
                XmlNodeList nCompname = nodo.GetElementsByTagName("comp-name");
                XmlNodeList nAlias = nodo.GetElementsByTagName("alias");
                XmlNodeList nEmail = nodo.GetElementsByTagName("email");
                XmlNodeList nProfile = nodo.GetElementsByTagName("profile");
                XmlNodeList nProfilename = nodo.GetElementsByTagName("profilename");
                XmlNodeList nGroup = nodo.GetElementsByTagName("group");


                DataRow fila;
                fila = result.Tables[0].NewRow();
                fila["user"] = nUser[0].InnerText;
                fila["name"] = nName[0].InnerText;
                fila["lastname"] = nLastname[0].InnerText;
                fila["comp-name"] = nCompname[0].InnerText;
                fila["alias"] = nAlias[0].InnerText;
                fila["email"] = nEmail[0].InnerText;
                fila["profile"] = nProfile[0].InnerText;
                fila["profilename"] = nProfilename[0].InnerText;
                fila["group"] = nGroup[0].InnerText;
                result.Tables[0].Rows.Add(fila);
            }

        }
        catch (Exception e)
        {
            Utility.writeError(e.Message);
            result = null;
        }
        return result;
    }
    public static DataSet getOpcionesbyApp(string sdatos)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("oap_id");
        result.Tables["Tabla"].Columns.Add("oap_nombre");
        result.Tables["Tabla"].Columns.Add("oap_permiso");
     
        try
        {

            XmlDocument xDoc = new XmlDocument();

            xDoc.Load(new StringReader(sdatos));

            XmlElement datosrespuesta = xDoc.DocumentElement;

            XmlNodeList users = xDoc.GetElementsByTagName("lista_opciones");

            XmlNodeList lista = ((XmlElement)users[0]).GetElementsByTagName("opcion");

            foreach (XmlElement nodo in lista)
            {

                XmlNodeList nUser = nodo.GetElementsByTagName("oap_id");
                XmlNodeList nName = nodo.GetElementsByTagName("oap_nombre");
                XmlNodeList nPermiso = nodo.GetElementsByTagName("oap_permiso");
                DataRow fila;
                fila = result.Tables[0].NewRow();
                fila["oap_id"] = nUser[0].InnerText;
                fila["oap_nombre"] = nName[0].InnerText;
                fila["oap_permiso"] = nPermiso[0].InnerText;
                result.Tables[0].Rows.Add(fila);
                
            }

        }
        catch (Exception e)
        {
            result = null;


        }
        return result;
    }

    public string formatHour(string strin) {
        string result;
        result = DateTime.Parse(strin).Hour.ToString() + ":" + DateTime.Parse(strin).Minute.ToString();
        return result;
    
    }
    public string formatDate(string strin) {
        string result;
        CultureInfo ci = new CultureInfo("en-US");
        result = DateTime.Parse(strin, ci).Date.ToShortDateString();

        return result;
    }
    public static string formatNumber(double fee) {
        
        string result;
        try
        {
            CultureInfo ci = new CultureInfo("en-US");
            string browser = HttpContext.Current.Request.Browser.Browser;
            
            //result = String.Format("{0:#.00}", fee);
            //result=   string.Format("{0:0.##}", fee);
            result = fee.ToString("##0.00;(##0.00);0.00");

            if (browser != "IE")
            {
                result = result.Replace(",", ".");
            }

            //result = result.ToString(ci);
        }catch(Exception ex){
            Utility.writeError("No se puede convertir el double "+fee+ "para darle formato Numerico"+ex.Message);
            result = "0.00";
        }
        return result;

    }
    public static string formatNumber(string fee)
    {

        string result;
        try
        {
            CultureInfo ci = new CultureInfo("en-US");
            // result = String.Format("{0:#.00}", fee);
            result = string.Format("{0:0.00}", fee);
            
            // result = result.ToString(ci);
        }
        catch (Exception ex)
        {
            Utility.writeError("No se puede convertir el double " + fee + "para darle formato Numerico" + ex.Message);
            result = "0.00";
        }
        return result;

    }
   


   public static string HoraAMPMtoFormato24horas(string horaformato12, string AMoPM)
    //convierte una hora en formato AMPM a formato de 24 horas
    {
        string input = horaformato12 + AMoPM,str1=null,str2=null;
        string sresult = null;
        sresult = "00:00";
 
 
        try
        {
 
 
            DateTime time = DateTime.Parse(input);
            int hour24 = int.Parse(time.ToString("HH"));
            int minute = int.Parse(time.ToString("mm"));
            str1 = string.Format("{0}", hour24);
            if (hour24 < 10)
            {
 
                str1 = "0" + str1;
 
            }
            str2 = string.Format("{0}", minute);
            if (minute < 10)
            {
                str2 = "0" + str2;
            }
            sresult = str1 + ":" + str2;
        }
 
        catch (Exception e)
        {
            Console.WriteLine("Error ! Not a valid time format...");
 
        }
       
        return sresult;
    }

    public  static RE_GenericBean Hora24horastoFormatoAMPM(string horaformato)
    //convierte una hora en format 24 horas a formato AMPM   
   {
        RE_GenericBean result=new RE_GenericBean();
        try
        {
 
            string input = horaformato,str1,str2;
            string AMPM = "AM";
            DateTime time = DateTime.Parse(input);
            int hour24 = int.Parse(time.ToString("HH"));
            if (hour24 > 11)
            {
                AMPM = "PM";
                if (hour24 != 12) { hour24 = hour24 - 12; }
                
            }
            if (hour24 > 23)
            {
                AMPM = "AM";
                hour24 = hour24 - 12;
            }
 
 
            int minute = int.Parse(time.ToString("mm"));
            str1 = string.Format("{0}", hour24);
           
            if (hour24 < 10)
            {
 
                str1 = "0" + str1;
            }
 
            str2 = string.Format("{0}", minute);
            if (minute < 10)
            {
 
                str2 = "0" + str2;
 
            }
 
 
            result.strC1 = str1 + ":" + str2;
            result.strC2 = AMPM;
        }
        catch (Exception e)
        {
            Console.WriteLine("Error ! Not a valid time format...");
 
        }
        return result;
 
    }

    public static bool validarEmail(string email)
    {
        bool result= true;
        string[] emailsarray= email.Split(';');
        string expresion = "\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";

        foreach (string onemail in emailsarray)
        {
        if (Regex.IsMatch(onemail, expresion))
        {
            if (Regex.Replace(onemail, expresion, String.Empty).Length == 0)
            { result= result & true; }
            else
            { result = result & false; }
        }
        else
        { result= result && false; }
    }
    return result;
    }

    public static int ValidateDate(string date)
    {// retorna 0 si la fecha es incorreta; 1 si si la fecha es igual, y 2 si la fecha es posterior (correcta)
        try
        {
            string[] dateParts = date.Split('/');
            string browser = HttpContext.Current.Request.Browser.Browser;

            DateTime testDate = new
            DateTime(Convert.ToInt32(dateParts[2]), Convert.ToInt32(dateParts[0]), Convert.ToInt32(dateParts[1]));
            /*if (browser != "IE")
            {
                date = dateParts[1] + "/" + dateParts[0] + "/" + dateParts[2];
            }*/
            DateTime nowdate = DateTime.Today;
           
            DateTime newdate = DateTime.Parse(testDate.ToString());
           
           
           // string auxdate=nowdate.Date.ToString();
            //nowdate=DateTime.Parse(auxdate);
            if (newdate == nowdate) { return 2; }
            else if (newdate > nowdate) { return 1; }
            else { return 0; }
        }
        catch (Exception ex)
        {
            Utility.writeError(ex.Message + ex.StackTrace);
            return 0;
        }
    }
    public static int isTomorrow(string date)
    {// retorna 0 si la fecha del parametro no corresponde a manana; 1 si si 
        try
        {
            string[] dateParts = date.Split('/');
            string browser = HttpContext.Current.Request.Browser.Browser;

            DateTime testDate = new
            DateTime(Convert.ToInt32(dateParts[2]), Convert.ToInt32(dateParts[0]), Convert.ToInt32(dateParts[1]));
            /*if (browser != "IE")
            {
                date = dateParts[1] + "/" + dateParts[0] + "/" + dateParts[2];
            }*/
            DateTime nowdate = DateTime.Today;

            DateTime newdate = DateTime.Parse(testDate.ToString());


            // string auxdate=nowdate.Date.ToString();
            //nowdate=DateTime.Parse(auxdate);
            if (newdate == nowdate.AddDays(1)) { return 1; }
            else { return 0; }
        }
        catch (Exception ex)
        {
            Utility.writeError(ex.Message + ex.StackTrace);
            return 0;
        }
    }

    public static int ValidarHora(string hora)
    {
        try
        {
            int auxt = 0;            
            string[] timeParts = hora.Split(':');

            if (Convert.ToInt32(timeParts[0]) >= 0)
            {
                if (Convert.ToInt32(timeParts[0]) <= 24)
                {
                    if (Convert.ToInt32(timeParts[1]) >= 0)
                    {
                        if (Convert.ToInt32(timeParts[1]) <= 59)
                        {
                            bool isOK = Regex.IsMatch(hora, @"[0-2][0-9]\:[0-6][0-9]");
                            if (isOK)
                            {
                                DateTime newtime = DateTime.Parse(hora);
                                DateTime oldtime = DateTime.Now;
                                if(newtime>=oldtime)
                                {auxt=1;}
                                else{return 0;}
                            }
                        }

                    }

                }
            }
            return auxt;
        }
        catch
        {

            return 0;
        }

    }


    public static string getsrtDate(string strdatein) {
       
        string result = "";
        if (!strdatein.Equals("")){
        try
        {
            DateTime re = DateTime.Parse(strdatein);
            result = re.ToShortDateString();
            
        }
        catch (Exception e) { Utility.writeError(e.Message); result = "";}
        }
        return result;
    }

    public static string getsrtTime(string strdatein) {
        string result = "";
        if (!strdatein.Equals(""))
        {
            try
            {
                DateTime re = DateTime.Parse(strdatein);
                result = re.ToShortTimeString();
            }
            catch (Exception e) { Utility.writeError(e.Message); result = ""; }
        }
        return result;

    }
    public static DataSet getCompanies(string sdatos)
    {//parsea xml de webservice todas las companias
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("com_id");
        result.Tables["Tabla"].Columns.Add("com_nombre");
        result.Tables["Tabla"].Columns.Add("com_url");
        result.Tables["Tabla"].Columns.Add("com_phone");
        result.Tables["Tabla"].Columns.Add("com_contacts");
        if (!sdatos.Equals(""))
        {
            try
            {

                XmlDocument xDoc = new XmlDocument();

                xDoc.Load(new StringReader(sdatos));

                XmlElement datosrespuesta = xDoc.DocumentElement;

                XmlNodeList users = xDoc.GetElementsByTagName("lista_companies");
                XmlNodeList lista = ((XmlElement)users[0]).GetElementsByTagName("datos_company");

                foreach (XmlElement nodo in lista)
                {

                    XmlNodeList nUser = nodo.GetElementsByTagName("com_id");
                    XmlNodeList nName = nodo.GetElementsByTagName("com_nombre");
                    XmlNodeList nUrl = nodo.GetElementsByTagName("com_url");
                    XmlNodeList nPhone = nodo.GetElementsByTagName("com_phone");
                    XmlNodeList nContacts = nodo.GetElementsByTagName("com_contacts");

                    DataRow fila;
                    fila = result.Tables[0].NewRow();
                    fila["com_id"] = nUser[0].InnerText;
                    fila["com_nombre"] = nName[0].InnerText;
                    fila["com_url"] = nUrl[0].InnerText;
                    fila["com_phone"] = nPhone[0].InnerText;
                    fila["com_contacts"] = nContacts[0].InnerText;
                    result.Tables[0].Rows.Add(fila);


                }

            }
            catch (Exception e)
            {
                Utility.writeError(e.Message + e.StackTrace);
                result = null;


            }
        }
        return result;
    }


    public static string QuitarCaracteresNoNumericos(string cadena)
    {

        int cont = 0;

        string numeros = "0123456789";

        string cadenaResult = "";



        while (cont < cadena.Length)
        {

            int cont2 = 0;

            while (cont2 < numeros.Length)
            {

                if (cadena[cont] == numeros[cont2])

                    cadenaResult = cadenaResult + cadena[cont];

                cont2++;

            }

            cont++;

        }

        return cadenaResult;

    }

    public static DataSet getAccounts(string sdatos)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("acc_id");
        result.Tables["Tabla"].Columns.Add("acc_nombre");
        result.Tables["Tabla"].Columns.Add("acc_initial");

        try
        {

            XmlDocument xDoc = new XmlDocument();

            xDoc.Load(new StringReader(sdatos));

            XmlElement datosrespuesta = xDoc.DocumentElement;

            XmlNodeList users = xDoc.GetElementsByTagName("lista_account");
            XmlNodeList lista = ((XmlElement)users[0]).GetElementsByTagName("datos_account");

            foreach (XmlElement nodo in lista)
            {

                XmlNodeList nUser = nodo.GetElementsByTagName("acc_id");
                XmlNodeList nName = nodo.GetElementsByTagName("acc_nombre");
                XmlNodeList nInitial = nodo.GetElementsByTagName("acc_initial");

                DataRow fila;
                fila = result.Tables[0].NewRow();
                fila["acc_id"] = nUser[0].InnerText;
                fila["acc_nombre"] = nName[0].InnerText;
                fila["acc_initial"] = nInitial[0].InnerText;

                result.Tables[0].Rows.Add(fila);


            }

        }
        catch (Exception e)
        {
            Utility.writeError(e.Message + e.StackTrace);
            result = null;


        }
        return result;
    }

    public static string toCapital(string strin) {


        int cont = 0;
        string result = "";
        bool encontrado = false;

        strin = strin.TrimStart();
        strin = strin.TrimEnd();

        string[] cad = strin.Split(' ');


        for (int aux = 0; aux < strin.Length; aux++)
        {
            if (strin[aux] == ' ')
            {
                encontrado = true;
            }
        }


        if (strin != null)
        {
            if (encontrado == true)
            {
                while (cont < cad.Length)
                {
                    if (cad[cont] != "")
                        result = result + " " + cad[cont].ToUpper().Substring(0, 1) + cad[cont].ToLower().Substring(1, cad[cont].ToString().Length - 1);

                    cont++;
                }
            }
            else
            {
                if (strin == "")
                    result = "";
                else
                    result = strin.ToUpper().Substring(0, 1) + strin.ToLower().Substring(1, strin.ToString().Length - 1);
            }
        }
        else
            result = "";

        return result.TrimStart();
  
    }

    public static string formatDateMMDD(string fec)
    {
        try
        {
            DateTime fecha = DateTime.Parse(fec);
            string mes = fecha.Month.ToString();
            string dia = fecha.Day.ToString();
            if (int.Parse(mes) < 10)
                mes = "0" + mes;
            if (int.Parse(dia) < 10)
                dia = "0" + dia;
            string fechaMMDD = mes + "/" + dia;
            return fechaMMDD;
        }
        catch (Exception e)
        {
            //writeError(e.Message);
            //writeError("No se aplicoformato a " + fec + " " + e.StackTrace);
            return fec;
        }
    }
    public static string formatDateMMDDYY(string fec)
    {
        if (!fec.Equals(""))
        {
            try
            {
                DateTime fecha = DateTime.Parse(fec);
                string fechaMMDD = fecha.ToUniversalTime().ToShortDateString();
                //string fechaMMDD = fecha.Month.ToString() + "/" + fecha.Day.ToString() + "/" + fecha.Year.ToString().Substring(2, 2); ;
                return fechaMMDD;
            }
            catch (Exception e)
            {
                writeError("No se aplicoformato a " + fec + " " + e.StackTrace);
               
            }
        }
        return fec;
    }

    public static string recortarString(string comm, int longitudTexto)
    {
        if (longitudTexto <= comm.Length)
        {
            comm = comm.Substring(0, longitudTexto);
        }
        return comm;
    }

    public static RE_GenericBean getNameCampoTablaByProcessname(string processname) {
        RE_GenericBean result = new RE_GenericBean();
        
        switch (processname.ToUpper())
        {
            case "PHOTOS EXT":
                result.strC1 = "ord_driver";
                result.strC2 = "ord_driver_done";
                result.strC3 ="ord_driver_date";
                result.strC4 ="ord_driver_time";


                break;

            case "PHOTOS INT":
                result.strC1 = "ord_driver";
                result.strC2 = "ord_driver_done";
                result.strC3 = "ord_driver_date";
                result.strC4 = "ord_driver_time";


                break;
            case "DATA ENTRY":
                result.strC1 = "ord_processor";
                result.strC2 = "ord_processor_done";
                result.strC3 = "ord_processor_date";
                result.strC4 = "ord_processor_time";
                break;
            case "QC CHECK":
                result.strC1 = "ord_qc";
                result.strC2 = "ord_qc_done";
                result.strC3 ="ord_qc_date";
                result.strC4 ="ord_qc_time";
                break;
            case "COMP SEARCH":
                result.strC1 = "ord_agent";
                result.strC2 = "ord_agent_done";
                result.strC3 ="ord_agent_date";
                result.strC4 ="ord_agent_time";
                break;
            case "SUBMITTED":
                result.strC1 = "ord_subby";
                result.strC2 = "ord_submitted_done";
                result.strC3 ="ord_submitted_date";
                result.strC4 ="ord_submitted_time";
                break;
            case "REKEY WITH PHOTOS":
                result.strC1 = "ord_driver";
                result.strC2 = "ord_driver_done";
                result.strC3 ="ord_driver_result.srtC3";
                result.strC4 ="ord_driver_time";


                break;
            case "RESUBMITTED":
                result.strC1 = "ord_resubby";
                result.strC2 = "ord_resubmitted_done";
                result.strC3 ="ord_submitted_result.srtC3";
                result.strC4 ="ord_submitted_time";
                break;
            case "DATA ENTRY QC":
                result.strC1 = "ord_dataqc";
                result.strC2 = "ord_dataqc_done";
                result.strC3 ="ord_dataqc_result.srtC3";
                result.strC4 ="ord_dataqc_time";
                break;
        }

        
        return result;
    
    }

    public static bool validarArchivoPDFJPG(string filename)
    {
        string expresion = "^.*\\.(jpg|JPG|pdf|PDF|jpeg|JPEG)$";

        if (Regex.IsMatch(filename, expresion))
        {
            if (Regex.Replace(filename, expresion, String.Empty).Length == 0)
            { return true; }
            else
            { return false; }
        }
        else
        { return false; }
    }

    public static string validarMoneda(string valor)
    {
        string cantidad = "";
        if (valor.IndexOf("$") == -1 && valor.IndexOf(",") == -1)
        {
            //valor = "$" + valor.Trim();
            char[] arr = valor.ToCharArray(0, valor.Length);
            for (int a = valor.Length-1; a >= 0; a-=3)
            {
                cantidad = cantidad +","+ valor.Substring(a - 3, 3);
            }
        }
        return cantidad;
    }


    public static DataSet getPerfiles(string sdatos)
    {//devuelve un dataset con los perfiles de la app
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("per_id");
        result.Tables["Tabla"].Columns.Add("per_nombre");
        try
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(new StringReader(sdatos));
            XmlElement datosrespuesta = xDoc.DocumentElement;

            XmlNodeList users = xDoc.GetElementsByTagName("lista_perfiles");
            XmlNodeList lista = ((XmlElement)users[0]).GetElementsByTagName("perfil");

            foreach (XmlElement nodo in lista)
            {

                XmlNodeList nID = nodo.GetElementsByTagName("perfilID");
                XmlNodeList nName = nodo.GetElementsByTagName("perfilNombre");
                DataRow fila;
                fila = result.Tables[0].NewRow();
                fila["per_id"] = nID[0].InnerText;
                fila["per_nombre"] = nName[0].InnerText;
                result.Tables[0].Rows.Add(fila);
            }

        }
        catch (Exception e)
        {
            result = null;
        }
        return result;
    }

    public static DataSet getPerfilesPermiso(string sdatos)
    {//devuelve un dataset con los perfiles de la app
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("per_id");
        result.Tables["Tabla"].Columns.Add("per_nombre");
        result.Tables["Tabla"].Columns.Add("per_permiso");
        result.Tables["Tabla"].Columns.Add("per_restricted");
        result.Tables["Tabla"].Columns.Add("per_pagina");
        try
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(new StringReader(sdatos));
            XmlElement datosrespuesta = xDoc.DocumentElement;

            XmlNodeList users = xDoc.GetElementsByTagName("lista_perfiles");
            XmlNodeList lista = ((XmlElement)users[0]).GetElementsByTagName("perfil");

            foreach (XmlElement nodo in lista)
            {

                XmlNodeList nID = nodo.GetElementsByTagName("perfilID");
                XmlNodeList nName = nodo.GetElementsByTagName("perfilNombre");
                XmlNodeList nPermiso = nodo.GetElementsByTagName("perfilPermiso");
                XmlNodeList nRestricted = nodo.GetElementsByTagName("perfilRestricted");
                XmlNodeList nPagina = nodo.GetElementsByTagName("perfilPagina");
                DataRow fila;
                fila = result.Tables[0].NewRow();
                fila["per_id"] = nID[0].InnerText;
                fila["per_nombre"] = nName[0].InnerText;
                fila["per_permiso"] = nPermiso[0].InnerText;
                fila["per_restricted"] = nRestricted[0].InnerText;
                fila["per_pagina"] = nPagina[0].InnerText;

                result.Tables[0].Rows.Add(fila);
            }

        }
        catch (Exception e)
        {
            result = null;
        }
        return result;
    }


    public static int deleteImage(string p)
    {//borra una foto del servidor
        int result = 0;
        try
        {

            
            string destinationFile = HttpContext.Current.Server.MapPath("~\\data\\photos\\" + p);
            System.IO.File.Delete(destinationFile);
            result = 1;
        }
        catch (Exception ex)
        {
            writeError(ex.Message + " " + ex.StackTrace);
            HttpContext.Current.Response.Write("<" + "script language='javascript'>");
            HttpContext.Current.Response.Write("alert('Image not Moved .');");
            HttpContext.Current.Response.Write("<" + "/script>");


        }
        return result;
    }

    public static int deletePhoto(int p)
    {
        throw new NotImplementedException();
    }

    public static DataSet getTodosUsuarios(string datos)
    {//DEVUELVE UN DATASET CON TODOS LOS USUARIOS
        DataSet perfiles = getPerfiles(datos);
        DataSet usuarios = new DataSet();
        int cont=0;
        string rxml = null;

        if (perfiles != null)
        {
            for (int a = 0; a < perfiles.Tables[0].Rows.Count; a++)
            {
                string aux = "", aux1 = "";
                int usperfil=int.Parse(perfiles.Tables[0].Rows[a][0].ToString());
                try
                {
                    
                    com.bpophotos.www.Service service = new com.bpophotos.www.Service();
                    aux = service.UsuariosPorPerfil(usperfil);
                    if (a > 0) {  if(!rxml.Equals("")){ aux = aux.Replace("<?xml version=\"1.0\" encoding=\"utf-8\" ?><lista_usuarios>", "");} }
                    if (a < perfiles.Tables[0].Rows.Count - 1) { aux = aux.Replace("</lista_usuarios>", ""); }
                    else
                    {
                        aux1 = service.UsuariosPorPerfil(1);
                        aux1 = aux1.Replace("<?xml version=\"1.0\" encoding=\"utf-8\" ?><lista_usuarios>", "");
                        aux = aux.Replace("</lista_usuarios>", "");
                        aux = aux + aux1;
                        aux1 = service.UsuariosPorPerfil(0);
                        aux1 = aux1.Replace("<?xml version=\"1.0\" encoding=\"utf-8\" ?><lista_usuarios>", "");
                        aux = aux.Replace("</lista_usuarios>", "");
                        aux = aux + aux1;
                    }
                }
                catch (Exception ex) { Utility.writeError(ex.Message); }

                rxml = rxml + aux ;
            }
            string aux2 = rxml.Replace("</lista_usuarios>", "");
            rxml = aux2 + "</lista_usuarios>";
                usuarios = getUsuariosporPerfil(rxml);
            if (usuarios != null) { cont = usuarios.Tables[0].Rows.Count; }
        }
        return usuarios;
    }

    public static DataSet getUsuEmployee(string datos)
    {//DEVUELVE UN DATASET CON TODOS LOS USUARIOS EMPLOYEE
        DataSet perfiles = getPerfiles(datos);
        DataSet usuarios = new DataSet();
        int cont = 0;
        string rxml = null;

        if (perfiles != null)
        {
            for (int a = 0; a < perfiles.Tables[0].Rows.Count; a++)
            {
                string aux = "", aux1 = "";
                int usperfil = int.Parse(perfiles.Tables[0].Rows[a][0].ToString());
                if (usperfil != 2)
                {
                    try
                    {
                        com.bpophotos.www.Service service = new com.bpophotos.www.Service();
                        aux = service.UsuariosPorPerfil(usperfil);
                        if (a > 0) { if (!rxml.Equals("")) { aux = aux.Replace("<?xml version=\"1.0\" encoding=\"utf-8\" ?><lista_usuarios>", ""); } }
                         if (a < perfiles.Tables[0].Rows.Count - 1) { aux = aux.Replace("</lista_usuarios>", ""); }
                        aux = aux + aux1;
                    }
                    catch (Exception ex) { Utility.writeError(ex.Message); }

                    rxml = rxml + aux;
                }
            }
            if (!rxml.Contains("</lista_usuarios>")){rxml+="</lista_usuarios>";}
            usuarios = getUsuariosporPerfil(rxml);
            if (usuarios != null) { cont = usuarios.Tables[0].Rows.Count; }
        }
        return usuarios;
    }

    public static DataSet getUsuClient(string datos)
    {//DEVUELVE UN DATASET CON TODOS LOS USUARIOS CLIENTES
        DataSet usuarios = new DataSet();
        int cont = 0;
        string rxml = null;

        try
        {
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            rxml = service.UsuariosPorPerfil(1);
        }
        catch (Exception ex) { Utility.writeError(ex.Message); }

        usuarios = getUsuariosporPerfil(rxml);
        
        if (usuarios != null) { cont = usuarios.Tables[0].Rows.Count; }
        
        return usuarios;
    }

    public static DataSet getUsuVendor(string datos)
    {//DEVUELVE UN DATASET CON TODOS LOS USUARIOS VENDOR
        DataSet usuarios = new DataSet();
        int cont = 0;
        string rxml = null;

        try
        {
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            rxml = service.UsuariosPorPerfil(2);
        }
        catch (Exception ex) { Utility.writeError(ex.Message); }

        usuarios = getUsuariosporPerfil(rxml);

        if (usuarios != null) { cont = usuarios.Tables[0].Rows.Count; }

        return usuarios;
    }

    public static DataSet getUsuInv(string datos)
    {//DEVUELVE UN DATASET CON TODOS LOS USUARIOS INV
        DataSet usuarios = new DataSet();
        int cont = 0;
        string rxml = null;

        try
        {
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            rxml = service.UsuariosPorPerfil(0);
        }
        catch (Exception ex) { Utility.writeError(ex.Message); }

        usuarios = getUsuariosporPerfil(rxml);

        if (usuarios != null) { cont = usuarios.Tables[0].Rows.Count; }

        return usuarios;
    }
    public static DataSet getUsuInactive(string datos)
    {//DEVUELVE UN DATASET CON TODOS LOS USUARIOS VENDOR
        DataSet usuarios = new DataSet();
        int cont = 0;
      

        usuarios = getUsuariosporPerfil(datos);

        if (usuarios != null) { cont = usuarios.Tables[0].Rows.Count; }

        return usuarios;
    }


    public static DataSet PharseXML_PerRes(string XMLPerRes)
    {
        DataSet result = new DataSet();
        result.Tables.Add("Tabla");
        result.Tables["Tabla"].Columns.Add("per_id");
        result.Tables["Tabla"].Columns.Add("page_id");
        result.Tables["Tabla"].Columns.Add("per_permiso");
        result.Tables["Tabla"].Columns.Add("per_restricted");
        try
        {
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(new StringReader(XMLPerRes));
            XmlElement datosrespuesta = xDoc.DocumentElement;

            XmlNodeList users = xDoc.GetElementsByTagName("lista_pageopp_permisos");
            XmlNodeList lista = ((XmlElement)users[0]).GetElementsByTagName("perfil");

            foreach (XmlElement nodo in lista)
            {

                XmlNodeList perID = nodo.GetElementsByTagName("idperfil");
                XmlNodeList pageID = nodo.GetElementsByTagName("idpage");
                XmlNodeList Permiso = nodo.GetElementsByTagName("permiso");
                XmlNodeList Restricted = nodo.GetElementsByTagName("restricted");
                DataRow fila;
                fila = result.Tables[0].NewRow();
                fila["per_id"] = perID[0].InnerText;
                fila["page_id"] = pageID[0].InnerText;
                fila["per_permiso"] = Permiso[0].InnerText;
                fila["per_restricted"] = Restricted[0].InnerText;

                result.Tables[0].Rows.Add(fila);
            }

        }
        catch (Exception e)
        {
            result = null;
        }
        return result;
        
    }

    public static DropDownList fillAgent(string vendorname, int nperfil, int nlen, DropDownList cblist)
    {// vendor name es cuando tiene un agente o proc o driver asignado lo va a seleccionar
        //nperfil desde que perfil debe empezar a pintar 1:driver, 2:proce , etc ver case
        //nlen es el rango 0 es todos y un numero pinta hasta ese rol ejemplo 8 pintaria hasta Admin
        //cblist es el combbox que se llenara

        int usperfil = 0;
        if (nlen == 0) { nlen = 15; }
        else { nlen = nperfil + (nlen - 1); }

        for (int a = nperfil; a <= nlen; a++)
        {
            ListItem list1 = new ListItem();
            switch (a)
            {
                case 1: { list1.Text = "Driver"; list1.Value = "2"; cblist.Items.Add(list1); cblist.Items[cblist.Items.Count - 1].Attributes.Add("disabled", "true"); usperfil = 2; break; }
                case 2: { list1.Text = "Photo Uploader"; list1.Value = "20"; cblist.Items.Add(list1); cblist.Items[cblist.Items.Count - 1].Attributes.Add("disabled", "true"); usperfil = 20; break; }
                case 3: { list1.Text = "Sr. Processor"; list1.Value = "3"; cblist.Items.Add(list1); cblist.Items[cblist.Items.Count - 1].Attributes.Add("disabled", "true"); usperfil = 3; break; }
                case 4: { list1.Text = "Jr. Processor"; list1.Value = "13"; cblist.Items.Add(list1); cblist.Items[cblist.Items.Count - 1].Attributes.Add("disabled", "true"); usperfil = 13; break; }
                case 5: { list1.Text = "Operator"; list1.Value = "4"; cblist.Items.Add(list1); cblist.Items[cblist.Items.Count - 1].Attributes.Add("disabled", "true"); usperfil = 4; break; }
                case 6: { list1.Text = "Agent"; list1.Value = "5"; cblist.Items.Add(list1); cblist.Items[cblist.Items.Count - 1].Attributes.Add("disabled", "true"); usperfil = 5; break; }
                case 7: { list1.Text = "QC Analist 2"; list1.Value = "6"; cblist.Items.Add(list1); cblist.Items[cblist.Items.Count - 1].Attributes.Add("disabled", "true"); usperfil = 6; break; }
                case 8: { list1.Text = "Admin"; list1.Value = "7"; cblist.Items.Add(list1); cblist.Items[cblist.Items.Count - 1].Attributes.Add("disabled", "true"); usperfil = 7; break; }
                case 9: { list1.Text = "Coordinator"; list1.Value = "8"; cblist.Items.Add(list1); cblist.Items[cblist.Items.Count - 1].Attributes.Add("disabled", "true"); usperfil = 8; break; }
                case 10: { list1.Text = "QC Manager"; list1.Value = "9"; cblist.Items.Add(list1); cblist.Items[cblist.Items.Count - 1].Attributes.Add("disabled", "true"); usperfil = 9; break; }
                case 11: { list1.Text = "Processing Manager"; list1.Value = "10"; cblist.Items.Add(list1); cblist.Items[cblist.Items.Count - 1].Attributes.Add("disabled", "true"); usperfil = 10; break; }
                case 12: { list1.Text = "Logistic Manager"; list1.Value = "11"; cblist.Items.Add(list1); cblist.Items[cblist.Items.Count - 1].Attributes.Add("disabled", "true"); usperfil = 11; break; }
                case 13: { list1.Text = "Photo Manager"; list1.Value = "21"; cblist.Items.Add(list1); cblist.Items[cblist.Items.Count - 1].Attributes.Add("disabled", "true"); usperfil = 21; break; }
                case 14: { list1.Text = "Operations Manager"; list1.Value = "12"; cblist.Items.Add(list1); cblist.Items[cblist.Items.Count - 1].Attributes.Add("disabled", "true"); usperfil = 12; break; }
                case 15: { list1.Text = "QC Analist 1"; list1.Value = "26"; cblist.Items.Add(list1); cblist.Items[cblist.Items.Count - 1].Attributes.Add("disabled", "true"); usperfil = 26; break; }
            }

            string rxml = null;
            try
            {
                com.bpophotos.www.Service service = new com.bpophotos.www.Service();
                rxml = service.UsuariosPorPerfil(usperfil);
            }
            catch (Exception ex) { Utility.writeError(ex.Message); }

            if (rxml != null || rxml != "")
            {

                DataSet usuariosperfil = Utility.getUsuariosporPerfil(rxml);
                if (usuariosperfil != null)
                {
                    for (int b = 0; b < usuariosperfil.Tables[0].Rows.Count; b++)
                    {
                        ListItem list2 = new ListItem();
                        string nombrecompleto = usuariosperfil.Tables[0].Rows[b][2].ToString() + " " + usuariosperfil.Tables[0].Rows[b][1].ToString();
                        list2.Value = usuariosperfil.Tables[0].Rows[b][6].ToString();
                        list2.Text = usuariosperfil.Tables[0].Rows[b][6].ToString() + "-" + Utility.toCapital(nombrecompleto);

                        //Comparando si el nombre ya existe
                        if (cblist.Items.IndexOf(cblist.Items.FindByValue(list2.Value)) == -1) { cblist.Items.Add(list2); }
                        if (vendorname == list2.Value)
                        {
                            cblist.SelectedValue = usuariosperfil.Tables[0].Rows[b][6].ToString();
                        }

                    }
                }
            }

        }

        return cblist;
    }

    public static DataSet getPermitPage(string xmlDatos)
    {// Devuelve un dataset con los permisos de las paginas y los permisos de las opciones de cada pagina

        DataSet permisos = new DataSet();
        permisos.Tables.Add("tablaPages");
        permisos.Tables["tablaPages"].Columns.Add("id_page");
        permisos.Tables["tablaPages"].Columns.Add("name_page");
        permisos.Tables["tablaPages"].Columns.Add("type");
        permisos.Tables["tablaPages"].Columns.Add("permit");
        permisos.Tables["tablaPages"].Columns.Add("image");
        permisos.Tables["tablaPages"].Columns.Add("id_section");
        permisos.Tables["tablaPages"].Columns.Add("id_option");

        permisos.Tables.Add("tablaOptions");
        permisos.Tables["tablaOptions"].Columns.Add("id_page");
        permisos.Tables["tablaOptions"].Columns.Add("name_option");
        permisos.Tables["tablaOptions"].Columns.Add("permit");
        permisos.Tables["tablaOptions"].Columns.Add("id_option");
        permisos.Tables["tablaOptions"].Columns.Add("id_section");
        permisos.Tables["tablaOptions"].Columns.Add("name_section");
        permisos.Tables["tablaOptions"].Columns.Add("orden");
       
        try
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(new StringReader(xmlDatos));
            XmlElement docRes = xmlDoc.DocumentElement;

            XmlNodeList pages = xmlDoc.GetElementsByTagName("pages");
            XmlNodeList lista=((XmlElement)pages[0]).GetElementsByTagName("page");

            foreach (XmlElement nodo in lista)
            {
                XmlNodeList idpage = nodo.GetElementsByTagName("id");
                XmlNodeList namepage = nodo.GetElementsByTagName("name");
                XmlNodeList typepage = nodo.GetElementsByTagName("type");
                XmlNodeList perpage = nodo.GetElementsByTagName("permit");
                XmlNodeList imapage = nodo.GetElementsByTagName("image");
                XmlNodeList idsection = nodo.GetElementsByTagName("idsection");
                XmlNodeList idopc = nodo.GetElementsByTagName("idopc");

                DataRow filaPages;
                filaPages = permisos.Tables[0].NewRow();
                filaPages["id_page"] = idpage[0].InnerText;
                filaPages["name_page"] = namepage[0].InnerText;
                filaPages["type"] = typepage[0].InnerText;
                filaPages["permit"] = perpage[0].InnerText;
                filaPages["image"] = imapage[0].InnerText;
                filaPages["id_section"] = idsection[0].InnerText;
                filaPages["id_option"] = idopc[0].InnerText;
                permisos.Tables[0].Rows.Add(filaPages);
            }

            XmlNodeList lista2 = ((XmlElement)pages[0]).GetElementsByTagName("option");

            foreach (XmlElement nodo in lista2)
            {
                XmlNodeList idpage = nodo.GetElementsByTagName("idpage");
                XmlNodeList nameoption = nodo.GetElementsByTagName("name");
                XmlNodeList peroption = nodo.GetElementsByTagName("permit");
                XmlNodeList idoption = nodo.GetElementsByTagName("idoption");
                XmlNodeList idsection = nodo.GetElementsByTagName("idsection");
                XmlNodeList namesection = nodo.GetElementsByTagName("namesection");
                XmlNodeList orden = nodo.GetElementsByTagName("orden");

                DataRow filaOptions;
                filaOptions = permisos.Tables[1].NewRow();
                filaOptions["id_page"] = idpage[0].InnerText;
                filaOptions["name_option"] = nameoption[0].InnerText;
                filaOptions["permit"] = peroption[0].InnerText;
                filaOptions["id_option"] = idoption[0].InnerText;
                filaOptions["id_section"] = idsection[0].InnerText;
                filaOptions["name_section"] = namesection[0].InnerText;
                filaOptions["orden"] = orden[0].InnerText;
                permisos.Tables[1].Rows.Add(filaOptions);
            }

        }
        catch (Exception e)
        {
            writeError(e.Message + e.StackTrace);
            permisos = null;
        }

        return permisos;

    }

    public static DataSet getPermitOption(string xmlDatos)
    {// Devuelve un dataset  de las opciones de cada pagina

        DataSet permisos = new DataSet();
       

        permisos.Tables.Add("tablaOptions");
        permisos.Tables["tablaOptions"].Columns.Add("parent_name");
        permisos.Tables["tablaOptions"].Columns.Add("id_option");
        permisos.Tables["tablaOptions"].Columns.Add("name_option");
        permisos.Tables["tablaOptions"].Columns.Add("permit");
       

        try
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(new StringReader(xmlDatos));
            XmlElement docRes = xmlDoc.DocumentElement;

            XmlNodeList pages = xmlDoc.GetElementsByTagName("options");
            XmlNodeList lista = ((XmlElement)pages[0]).GetElementsByTagName("option");

            foreach (XmlElement nodo in lista)
            {
                

                
                        XmlNodeList idoption = nodo.GetElementsByTagName("id");
                        XmlNodeList nameoption = nodo.GetElementsByTagName("name");
                        XmlNodeList peroption = nodo.GetElementsByTagName("permit");
                        XmlNodeList pagename = nodo.GetElementsByTagName("pagename");

                        DataRow filaoptions;
                        filaoptions = permisos.Tables[0].NewRow();
                        filaoptions["parent_name"] = pagename[0].InnerText;
                        filaoptions["id_option"] = idoption[0].InnerText;
                        filaoptions["name_option"] = nameoption[0].InnerText;
                        filaoptions["permit"] = peroption[0].InnerText;
                      
                        permisos.Tables[0].Rows.Add(filaoptions);
                    }
                }

           
        catch (Exception e)
        {
            writeError(e.Message + e.StackTrace);
            permisos = null;
        }

        return permisos;

    }
     public static RE_GenericBean getInfoUserbyInitial(string initial){
        RE_GenericBean result= new RE_GenericBean();
        DataSet usuEmployee = null; DataSet usuVendor= null;
         string rxml1= null;
       DataSet usuarios= (DataSet)HttpContext.Current.Session["Usuarios"];
         if (usuarios ==  null){
            com.bpophotos.www.Service  service = new com.bpophotos.www.Service();
             rxml1 = service.getPerfiles(1,1);
             if (rxml1!= null){
                 DataSet perfiles = Utility.getPerfiles(rxml1);
                 usuarios = Utility.getTodosUsuarios(rxml1);
                 usuVendor = Utility.getUsuVendor(rxml1);
             }
             service.Dispose();
         }
             if (usuarios!= null){
                 for (int ii = 0; ii <= (usuarios.Tables[0].Rows.Count - 1); ii++)
                 {
                     string dsinitial = usuarios.Tables[0].Rows[ii]["alias"].ToString();

                     if (initial.Equals(dsinitial))
                     {
                         result.strC1 = usuarios.Tables[0].Rows[ii]["name"].ToString() + " " + usuarios.Tables[0].Rows[ii]["lastname"].ToString();
                         result.strC2 = usuarios.Tables[0].Rows[ii]["profilename"].ToString();
                         result.strC3 = usuarios.Tables[0].Rows[ii]["user"].ToString();
                         result.strC4 = usuarios.Tables[0].Rows[ii]["group"].ToString();
                         result.strC5 = usuarios.Tables[0].Rows[ii]["comp-name"].ToString();
                         result.strC6 = usuarios.Tables[0].Rows[ii]["email"].ToString();
  
                     }
                 
             }
            
         }

            

                 

             
         
         return result;
     }

     public static void setVariablesSession()
     {
         DataSet companies = null, accounts = null, products = null, usuEmployee = null;
         string rxmlcompanies = null;
         DataSet usuGeneral;
         com.bpophotos.www.Service service = new com.bpophotos.www.Service();


         try
         {
             companies = (DataSet)HttpContext.Current.Session["companies"];
             accounts = (DataSet)HttpContext.Current.Session["accounts"];
             products = (DataSet)HttpContext.Current.Session["products"];
             usuEmployee = (DataSet)HttpContext.Current.Session["Usuarios"];
             if (products == null) { products = (DataSet)DB.GetProducts(); }
             if (companies == null)
             {
                 rxmlcompanies = service.getCompanies();
                 companies = Utility.getCompanies(rxmlcompanies);
             }
             if (accounts == null)
             {
                 string xmlaccount = service.getAccounts();
                 accounts = Utility.getAccounts(xmlaccount);
             }
             if (usuEmployee == null)
             {
                 string rxml1 = service.getPerfiles(1,1);
                 DataSet perfiles = Utility.getPerfiles(rxml1);
                 HttpContext.Current.Session["Perfiles"] = perfiles;
                 // Utility.writeError("Error Default " + rxml1);
                 usuEmployee = Utility.getTodosUsuarios(rxml1);
             }

             HttpContext.Current.Session["companies"] = companies;
             HttpContext.Current.Session["accounts"] = accounts;
             HttpContext.Current.Session["products"] = products;
             HttpContext.Current.Session["Usuarios"] = usuEmployee;


         }
         catch (Exception ex) { Utility.writeError(ex.Message); }
         finally
         {
             if (service != null) { service.Dispose(); }

         }
     }

     public static RE_GenericBean getPermisobyRuser(rUser ruser, int pageid)
     {
        
         RE_GenericBean result = new RE_GenericBean();
         if (ruser != null)
         {
            
             foreach (RE_GenericBean per in ruser.permisos)
             {
                 if (per.intC1 == pageid)
                 {
                     result.int64C1 = per.int64C1;
                     result.int64C2 = per.int64C2;
                 }
             }
         }
         return result;
     }

     public static DropDownList fillclients(DropDownList cbclient, string firstitem)
     {
         rUser ruser;
         try
         {
             string rxml = null;
             com.bpophotos.www.Service service = new com.bpophotos.www.Service();
             rxml = service.UsuariosPorPerfil(1);

             if (!rxml.Equals("") || rxml != null)
             {
                 DataSet dsclient = Utility.getUsuariosporPerfil(rxml);
                 ListItem listitem0 = new ListItem();
                 listitem0.Text = firstitem; listitem0.Value = "";
                 cbclient.Items.Add(listitem0);

                 ruser = (rUser)HttpContext.Current.Session["userid"];
                 for (int ii = 0; ii <= (dsclient.Tables[0].Rows.Count - 1); ii++)
                 {
                     ListItem listitem = new ListItem();
                     listitem.Text = dsclient.Tables[0].Rows[ii][6].ToString()+"-"+dsclient.Tables[0].Rows[ii][2].ToString() + " " + dsclient.Tables[0].Rows[ii][1].ToString();
                     listitem.Value = dsclient.Tables[0].Rows[ii][0].ToString();
                     cbclient.Items.Add(listitem);

                     if (ruser.getUsuarioId().Equals(listitem.Value))
                     {
                         cbclient.SelectedValue = listitem.Value;

                     }

                 }
             }
             service.Dispose();
             return cbclient;
         }
         catch (Exception ee)
         {
             Utility.writeError(ee.Message);
             return cbclient;
         }
     }


     public static DataSet getPermitMenu(string xmlDatos)
     {// Devuelve un dataset con los permisos del menu y los permisos de las opciones del menu

         DataSet permisos = new DataSet();
         permisos.Tables.Add("tablaMenu");
         permisos.Tables["tablaMenu"].Columns.Add("id");
         permisos.Tables["tablaMenu"].Columns.Add("page_id");
         permisos.Tables["tablaMenu"].Columns.Add("name");
         permisos.Tables["tablaMenu"].Columns.Add("permiso");
         permisos.Tables["tablaMenu"].Columns.Add("url");
         permisos.Tables["tablaMenu"].Columns.Add("target");
         permisos.Tables["tablaMenu"].Columns.Add("option");
         permisos.Tables["tablaMenu"].Columns.Add("orden");

         permisos.Tables.Add("tablaOptions");
         permisos.Tables["tablaOptions"].Columns.Add("id");
         permisos.Tables["tablaOptions"].Columns.Add("page_id");
         permisos.Tables["tablaOptions"].Columns.Add("menu_id");
         permisos.Tables["tablaOptions"].Columns.Add("name");
         permisos.Tables["tablaOptions"].Columns.Add("permiso");
         permisos.Tables["tablaOptions"].Columns.Add("url");
         permisos.Tables["tablaOptions"].Columns.Add("target");
         permisos.Tables["tablaOptions"].Columns.Add("option");
         permisos.Tables["tablaOptions"].Columns.Add("orden");

         permisos.Tables.Add("tablaSubOpc");
         permisos.Tables["tablaSubOpc"].Columns.Add("id");
         permisos.Tables["tablaSubOpc"].Columns.Add("option_id");
         permisos.Tables["tablaSubOpc"].Columns.Add("page_id");
         permisos.Tables["tablaSubOpc"].Columns.Add("name");
         permisos.Tables["tablaSubOpc"].Columns.Add("permiso");
         permisos.Tables["tablaSubOpc"].Columns.Add("url");
         permisos.Tables["tablaSubOpc"].Columns.Add("target");
         permisos.Tables["tablaSubOpc"].Columns.Add("orden");

         try
         {
             XmlDocument xmlDoc = new XmlDocument();
             xmlDoc.Load(new StringReader(xmlDatos));
             XmlElement docRes = xmlDoc.DocumentElement;

             XmlNodeList pages = xmlDoc.GetElementsByTagName("menus");
             XmlNodeList lista = ((XmlElement)pages[0]).GetElementsByTagName("menu");

             foreach (XmlElement nodo in lista)
             {
                 XmlNodeList idmenu = nodo.GetElementsByTagName("men_id");
                 XmlNodeList idpage = nodo.GetElementsByTagName("papp_id");
                 XmlNodeList menuname = nodo.GetElementsByTagName("men_name");
                 XmlNodeList menuper = nodo.GetElementsByTagName("opc_permiso");
                 XmlNodeList menuurl = nodo.GetElementsByTagName("men_url");
                 XmlNodeList mentar = nodo.GetElementsByTagName("men_target");
                 XmlNodeList menopc = nodo.GetElementsByTagName("men_option");
                 XmlNodeList menorden = nodo.GetElementsByTagName("men_orden");

                 DataRow filaMenu;
                 filaMenu = permisos.Tables[0].NewRow();
                 filaMenu["id"] = idmenu[0].InnerText;
                 filaMenu["page_id"] = idpage[0].InnerText;
                 filaMenu["name"] = menuname[0].InnerText;
                 filaMenu["permiso"] = menuper[0].InnerText;
                 filaMenu["url"] = menuurl[0].InnerText;
                 filaMenu["target"] = mentar[0].InnerText;
                 filaMenu["option"] = menopc[0].InnerText;
                 filaMenu["orden"] = menorden[0].InnerText;
                 permisos.Tables[0].Rows.Add(filaMenu);
             }

             XmlNodeList lista2 = ((XmlElement)pages[0]).GetElementsByTagName("submenu");

             foreach (XmlElement nodo in lista2)
             {
                 XmlNodeList idsumenu = nodo.GetElementsByTagName("mopc_id");
                 XmlNodeList idpage = nodo.GetElementsByTagName("papp_id");
                 XmlNodeList idmenu = nodo.GetElementsByTagName("men_id");
                 XmlNodeList sumenuname = nodo.GetElementsByTagName("mopc_name");
                 XmlNodeList sumenuper = nodo.GetElementsByTagName("opc_permiso");
                 XmlNodeList sumenuurl = nodo.GetElementsByTagName("mopc_url");
                 XmlNodeList sumenutar = nodo.GetElementsByTagName("mopc_target");
                 XmlNodeList sumenuopc = nodo.GetElementsByTagName("mopc_option");
                 XmlNodeList mopcorden = nodo.GetElementsByTagName("mopc_orden");

                 DataRow filaOptions;
                 filaOptions = permisos.Tables[1].NewRow();
                 filaOptions["id"] = idsumenu[0].InnerText;
                 filaOptions["page_id"] = idpage[0].InnerText;
                 filaOptions["menu_id"] = idmenu[0].InnerText;
                 filaOptions["name"] = sumenuname[0].InnerText;
                 filaOptions["permiso"] = sumenuper[0].InnerText;
                 filaOptions["url"] = sumenuurl[0].InnerText;
                 filaOptions["target"] = sumenutar[0].InnerText;
                 filaOptions["option"] = sumenuopc[0].InnerText;
                 filaOptions["orden"] = mopcorden[0].InnerText;
                 permisos.Tables[1].Rows.Add(filaOptions);
             }

             XmlNodeList lista3 = ((XmlElement)pages[0]).GetElementsByTagName("suboption");

             foreach (XmlElement nodo in lista3)
             {
                 XmlNodeList idsuoption = nodo.GetElementsByTagName("mopc_id");
                 XmlNodeList idsumenu = nodo.GetElementsByTagName("submenu_id");
                 XmlNodeList idpage = nodo.GetElementsByTagName("papp_id");
                 XmlNodeList suopcname = nodo.GetElementsByTagName("mopc_name");
                 XmlNodeList suopcper = nodo.GetElementsByTagName("opc_permiso");
                 XmlNodeList suopcurl = nodo.GetElementsByTagName("mopc_url");
                 XmlNodeList suopctar = nodo.GetElementsByTagName("mopc_target");
                 XmlNodeList suorden = nodo.GetElementsByTagName("sopcorden");

                 DataRow filaSuOptions;
                 filaSuOptions = permisos.Tables[2].NewRow();
                 filaSuOptions["id"] = idsuoption[0].InnerText;
                 filaSuOptions["option_id"] = idsumenu[0].InnerText;
                 filaSuOptions["page_id"] = idpage[0].InnerText;
                 filaSuOptions["name"] = suopcname[0].InnerText;
                 filaSuOptions["permiso"] = suopcper[0].InnerText;
                 filaSuOptions["url"] = suopcurl[0].InnerText;
                 filaSuOptions["target"] = suopctar[0].InnerText;
                 filaSuOptions["orden"] = suorden[0].InnerText;
                 permisos.Tables[2].Rows.Add(filaSuOptions);
             }
         }
         catch (Exception e)
         {
             writeError(e.Message + e.StackTrace);
             permisos = null;
         }

         return permisos;

     }

     public static DropDownList fillsector(DropDownList cb)
     {
         cb.Items.Clear();


         DataSet ds = DB.getSectors();
         if (ds != null)
         {
             cb.Items.Add("All");
             for (int i = 0; i <= (ds.Tables[0].Rows.Count - 1); i++)
             {
                 if (ds.Tables[0].Rows[i]["enable"].ToString().Equals("1"))
                 {
                     ListItem Li = new ListItem();
                     Li.Value = ds.Tables[0].Rows[i]["sector_id"].ToString();
                     Li.Text = ds.Tables[0].Rows[i]["name"].ToString().ToUpper();
                     cb.Items.Add(Li);
                 }
             }
         }
         return cb;
     }

    public static DropDownList fillCounties(DropDownList cb)
    {
        cb.Items.Clear();

        DataSet counties = DB.getAllCounties();
        //DataSet counties = DB.getCountiesbySector(sector);
        if (counties != null)
        {
            ListItem li = new ListItem();
            li.Text = "All"; li.Value = "All";
            cb.Items.Add(li);

            for (int i = 0; i <= (counties.Tables[0].Rows.Count - 1); i++)
            {
                if (!counties.Tables[0].Rows[i][3].ToString().ToUpper().Equals("0"))
                {
                    li = new ListItem();
                    li.Text = counties.Tables[0].Rows[i]["Name"].ToString();
                    li.Value = counties.Tables[0].Rows[i][0].ToString();
                    cb.Items.Add(li);

                }

            }
        }
        return cb;
    }

     public static DropDownList fillAreas(DropDownList cb)
     {
         cb.Items.Clear();

         DataSet areas = DB.getAreas();
         //DataSet counties = DB.getCountiesbySector(sector);
         if (areas != null)
         {
             ListItem li = new ListItem();
             li.Text = "All"; li.Value = "All";
             cb.Items.Add(li);

             for (int i = 0; i <= (areas.Tables[0].Rows.Count - 1); i++)
             {
                 if (!areas.Tables[0].Rows[i][2].ToString().ToUpper().Equals("0"))
                 {
                     li = new ListItem();
                     li.Text = areas.Tables[0].Rows[i][1].ToString();
                    li.Value = areas.Tables[0].Rows[i][0].ToString();
                     cb.Items.Add(li);

                 }

             }
         }
         return cb;
     }

     public static DataSet getPagesView(string xmlDatos)
     {// Devuelve un dataset con todas la paginas y su clasificacion

         DataSet pages = new DataSet();
         pages.Tables.Add("tablaPage");
         pages.Tables["tablapage"].Columns.Add("id");
         pages.Tables["tablapage"].Columns.Add("apl_id");
         pages.Tables["tablapage"].Columns.Add("page_id");
         pages.Tables["tablapage"].Columns.Add("name");
         pages.Tables["tablapage"].Columns.Add("url");
         pages.Tables["tablapage"].Columns.Add("type");

         pages.Tables.Add("tablaOptions");
         pages.Tables["tablaOptions"].Columns.Add("id");
         pages.Tables["tablaOptions"].Columns.Add("pg1_id");
         pages.Tables["tablaOptions"].Columns.Add("page_id");
         pages.Tables["tablaOptions"].Columns.Add("name");
         pages.Tables["tablaOptions"].Columns.Add("url");
         pages.Tables["tablaOptions"].Columns.Add("type");

         pages.Tables.Add("tablaSubOpc");
         pages.Tables["tablaSubOpc"].Columns.Add("id");
         pages.Tables["tablaSubOpc"].Columns.Add("pg2_id");
         pages.Tables["tablaSubOpc"].Columns.Add("page_id");
         pages.Tables["tablaSubOpc"].Columns.Add("name");
         pages.Tables["tablaSubOpc"].Columns.Add("url");
         pages.Tables["tablaSubOpc"].Columns.Add("type");

         try
         {
             XmlDocument xmlDoc = new XmlDocument();
             xmlDoc.Load(new StringReader(xmlDatos));
             XmlElement docRes = xmlDoc.DocumentElement;

             XmlNodeList page = xmlDoc.GetElementsByTagName("pages");
             XmlNodeList lista = ((XmlElement)page[0]).GetElementsByTagName("page");

             foreach (XmlElement nodo in lista)
             {
                 XmlNodeList id = nodo.GetElementsByTagName("id");
                 XmlNodeList apl = nodo.GetElementsByTagName("apl_id");
                 XmlNodeList idpage = nodo.GetElementsByTagName("papp_id");
                 XmlNodeList name = nodo.GetElementsByTagName("name");
                 XmlNodeList url = nodo.GetElementsByTagName("path");
                 XmlNodeList type = nodo.GetElementsByTagName("type");

                 DataRow filaPage;
                 filaPage = pages.Tables[0].NewRow();
                 filaPage["id"] = id[0].InnerText;
                 filaPage["apl_id"] = apl[0].InnerText;
                 filaPage["page_id"] = idpage[0].InnerText;
                 filaPage["name"] = name[0].InnerText;
                 filaPage["url"] = url[0].InnerText;
                 filaPage["type"] = type[0].InnerText;
                 pages.Tables[0].Rows.Add(filaPage);
             }

             XmlNodeList lista2 = ((XmlElement)page[0]).GetElementsByTagName("subpage");

             foreach (XmlElement nodo in lista2)
             {
                 XmlNodeList id = nodo.GetElementsByTagName("id");
                 XmlNodeList idpg = nodo.GetElementsByTagName("pg1_id");
                 XmlNodeList idpage = nodo.GetElementsByTagName("papp_id");
                 XmlNodeList name = nodo.GetElementsByTagName("name");
                 XmlNodeList url = nodo.GetElementsByTagName("path");
                 XmlNodeList type = nodo.GetElementsByTagName("type");

                 DataRow filaOptions;
                 filaOptions = pages.Tables[1].NewRow();
                 filaOptions["id"] = id[0].InnerText;
                 filaOptions["pg1_id"] = idpg[0].InnerText;
                 filaOptions["page_id"] = idpage[0].InnerText;
                 filaOptions["name"] = name[0].InnerText;
                 filaOptions["url"] = url[0].InnerText;
                 filaOptions["type"] = type[0].InnerText;
                 pages.Tables[1].Rows.Add(filaOptions);
             }

             XmlNodeList lista3 = ((XmlElement)page[0]).GetElementsByTagName("suboption");

             foreach (XmlElement nodo in lista3)
             {
                 XmlNodeList id = nodo.GetElementsByTagName("id");
                 XmlNodeList idpg = nodo.GetElementsByTagName("pg2_id");
                 XmlNodeList idpage = nodo.GetElementsByTagName("papp_id");
                 XmlNodeList name = nodo.GetElementsByTagName("name");
                 XmlNodeList url = nodo.GetElementsByTagName("path");
                 XmlNodeList type = nodo.GetElementsByTagName("type");

                 DataRow filaSuOptions;
                 filaSuOptions = pages.Tables[2].NewRow();
                 filaSuOptions["id"] = id[0].InnerText;
                 filaSuOptions["pg2_id"] = idpg[0].InnerText;
                 filaSuOptions["page_id"] = idpage[0].InnerText;
                 filaSuOptions["name"] = name[0].InnerText;
                 filaSuOptions["url"] = url[0].InnerText;
                 filaSuOptions["type"] = type[0].InnerText;
                 pages.Tables[2].Rows.Add(filaSuOptions);
             }
         }
         catch (Exception e)
         {
             writeError(e.Message + e.StackTrace);
             pages = null;
         }

         return pages;

     }




     public static RE_GenericBean parsePaypal(string datos)
     {
         string[] temp= datos.Split('&');
         RE_GenericBean result = new RE_GenericBean();
       
         string subject= "";
         string fee = "";
         string trantype = "";
         string ipnid = "";
         string paymentstatus = ""; string client = "";
         string item = "";
         ArrayList array = new ArrayList();
         for (int i = 0; i < temp.Length; i++ ) 
         {
             string[] temp2 = temp[i].ToString().Split('=');
             if (temp2[0].ToString().Equals("transaction_subject")) { 
                 subject = temp2[1];
 

             }
             if (temp2[0].ToString().Equals("payment_fee"))
             {
                 fee = temp2[1];
             }
             if (temp2[0].ToString().Equals("txn_type"))
             {
                 trantype = temp2[1];
             }
             if (temp2[0].ToString().Equals("ipn_track_id"))
             {
                 ipnid = temp2[1];
             }
             if (temp2[0].ToString().Equals("payment_status"))
             {
                 paymentstatus = temp2[1];
             }
             if (temp2[0].ToString().Contains("item_number"))
             {
                 if (!item.Equals("")) { item += ";"; }
                 item+=temp2[1].ToString();

             }
             
         }
         result.strC1 = trantype;//trantype
         result.strC2 = fee;//payment_fee
         result.strC3 = subject;//subject
         result.strC4 = ipnid;//ipn id
         result.strC5 = paymentstatus;//paymentstatus
         result.strC6 = item;//items
         return result;

     }

     public static DropDownList fillaccounts(DropDownList cb, string titleindex)
     {
         try
         {
             DataSet dsacc = (DataSet)HttpContext.Current.Session["Accounts"];
             if (dsacc == null)
             {
                 string rxml = null;
                 com.bpophotos.www.Service service = new com.bpophotos.www.Service();
                 rxml = service.getAccounts();


                 if (!rxml.Equals("") || rxml != null)
                 {
                     dsacc = Utility.getAccounts(rxml);
                     HttpContext.Current.Session["Accounts"] = dsacc;
                 }
                 service.Dispose();
             }
             ListItem listitem0 = new ListItem();
             listitem0.Text = titleindex; listitem0.Value = "";
             cb.Items.Add(listitem0);


             for (int ii = 0; ii <= (dsacc.Tables[0].Rows.Count - 1); ii++)
             {
                 ListItem listitem = new ListItem();
                 listitem.Text = dsacc.Tables[0].Rows[ii][1].ToString();
                 listitem.Value = dsacc.Tables[0].Rows[ii][0].ToString();
                 cb.Items.Add(listitem);

             }
         }




         catch (Exception ee)
         {
             Utility.writeError(ee.Message);
             
         }
         return cb;
     }
     public static DropDownList fillcompanies(DropDownList cb, string titleindex)
     {
         try
         {
             DataSet dsacc = (DataSet)HttpContext.Current.Session["companies"];
             if (dsacc == null)
             {
                 string rxml = null;
                 com.bpophotos.www.Service service = new com.bpophotos.www.Service();
                 rxml = service.getCompanies();


                 if (!rxml.Equals("") || rxml != null)
                 {
                     dsacc = Utility.getAccounts(rxml);
                     HttpContext.Current.Session["companies"] = dsacc;
                 }
                 service.Dispose();
             }
             ListItem listitem0 = new ListItem();
             listitem0.Text = titleindex; listitem0.Value = "";
             cb.Items.Add(listitem0);


             for (int ii = 0; ii <= (dsacc.Tables[0].Rows.Count - 1); ii++)
             {
                 ListItem listitem = new ListItem();
                 listitem.Text = dsacc.Tables[0].Rows[ii][1].ToString();
                 listitem.Value = dsacc.Tables[0].Rows[ii][0].ToString();
                 cb.Items.Add(listitem);

             }
         }




         catch (Exception ee)
         {
             Utility.writeError(ee.Message);

         }
         return cb;
     }
     public static string convertTime()
     {
         string time;
         try
         {
             time = DateTime.Now.ToShortTimeString();
             if (time.Contains("a.m.")) time = time.Replace("a.m.", "AM");
             else if (time.Contains("p.m.")) time = time.Replace("p.m.", "PM");
         }
         catch (Exception ee)
         {
             Utility.writeError(ee.Message);
             time = "00:00";
         }
         return time;
     }
     
}